package com.redhipps.hips.client.command;

import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.redhipps.hips.client.io.WriterCallback;
import com.redhipps.hips.client.model.DateTime;
import com.redhipps.hips.client.model.Schedule;
import com.redhipps.hips.client.widget.Dialogs;

public class CreateScheduleCommand extends HipsCommand<Schedule> {

  @Override
  public void execute(final AsyncCallback<Schedule> callback) {
    final WriterCallback<Schedule> writeCallback = new WriterCallback<Schedule>() {
      public void onFailure(Throwable caught) {
        GWT.log("Create institution failed", caught);
        callback.onFailure(caught);
      }
      public void onSuccess(List<Schedule> result) {
        GWT.log("Create institution successful", null);
        callback.onSuccess(result.get(0));
      }
    };
    final AsyncCallback<String> dialogCallback = new AsyncCallback<String>() {
      public void onFailure(Throwable caught) {
        GWT.log("Create institution failed", caught);
      }
      public void onSuccess(String result) {
        if (result == null || result.length() == 0) {
          callback.onSuccess(null);
          return;
        }
        try {
          Schedule model = new Schedule();
          String[] parts = result.split("-");
          DateTime date = new DateTime(
              Integer.parseInt(parts[0]),
              Integer.parseInt(parts[1]),
              Integer.parseInt(parts[2]),
              6, 0, 0);
          model.setStartTime(date);
          createSchedule(model, writeCallback);
        } catch (Exception e) {
          writeCallback.onFailure(e);
        }
      }
    };
    Dialogs.answer("New Schedule", "Specify {start_time: 2009-06-01}", dialogCallback);
  }

  public void createSchedule(Schedule model, WriterCallback<Schedule> callback)
      throws RequestException {
    ioService().create(context(), model, callback);
  }

}
